
#include <assert.h>

#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QFile>
#include <QResource>

#include "UiLoader.h"
#include <Network/NetworkAccessManager.h>

namespace TC
{
    namespace Utility
    {
        const char *hostAddress = "http://weizehua0403.vicp.cc:81/";

        UiLoader::UiLoader(QObject *parent /*= nullptr*/) : QObject(parent)
        {
            assert(_instance == nullptr);

            _instance = this;
        }

        UiLoader::~UiLoader()
        {
            _instance = nullptr;
        }

        void UiLoader::loadNewResourcesFromNetwork()
        {
			using namespace Network;
            thread_local NetworkAccessManager *manager = new NetworkAccessManager(nullptr);
            QObject::connect(manager, &NetworkAccessManager::finished, [=](QNetworkReply *reply)
            {
                qDebug() << "Remote Resource Downloaded, saving..." << endl;
                QFile f("qml.rcc");
                if (f.open(QFile::WriteOnly))
                {
                    f.write(reply->readAll());
					f.close();
					qDebug() << "Remote Resource saved to local." << endl;

                }
				else
				{
					qWarning() << "Remote Resource Downloaded, but failed to save." << endl;
				}
                //if (QResource::registerResource((uchar *)(new QByteArray(reply->readAll()))->constData(), "/Remote"))
                //{
                //    remoteLoaded = true;
                //    remoteLoadedChanged();
                //}
                manager->deleteLater();
            });
            manager->get(QNetworkRequest(QUrl(QString(hostAddress) + "qml.rcc")));
        }

        void UiLoader::loadNewReourcesFromLocal()
        {
            if (QFile::exists("qml.rcc"))
            {
                QFile f("qml.rcc");
                if (f.open(QFile::ReadOnly))
                {
                    auto data = new QByteArray(f.readAll());
                    if (QResource::registerResource((uchar *)data->constData(), "/Local"))
                    {
                        localLoaded = true;
                        localLoadedChanged();
                    }
					f.close();
                }
            }
        }

        void UiLoader::tryLoadNewResources()
        {
            loadNewReourcesFromLocal();
            loadNewResourcesFromNetwork();
        }

        UiLoader* UiLoader::instance()
        {
            if (_instance == nullptr)
                _instance = new UiLoader;
            return _instance;
        }

        UiLoader* UiLoader::_instance = nullptr;
    }
}